// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db_testAnswer = cloud.database().collection("testAnswer")
const db_test = cloud.database().collection("test")
const logger = cloud.logger()

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case "getMyTestData": //所有考试信息
      return getMyTestData(event)
      break;
    case "getUserAnswers": //所有答案信息
      return getUserAnswers(event)
      break;
    case "deleteAnswerById": //删除答案数据
      return deleteAnswerById(event);
      break;
    default:
      return {
        data: "请添加参数：action"
      };
      break;
  }
}
//获取我的考试数据
async function getMyTestData(event) {
  const wxContext = cloud.getWXContext()
  //获取所有管理员信息
  var adminList = await db_test.where({
    flag: 'admin'
  }).get()

  logger.error({
    adminList: adminList
  })

  var adminUsers = adminList.data[0].userIds;
  var isAdmin = false;
  for (let i = 0; i < adminUsers.length; i++) {
    if (adminUsers[i] == wxContext.OPENID)
      isAdmin = true
  }
  //获取所有个人答题
  var myTest = await db_testAnswer.where({
    _openid: wxContext.OPENID
  }).get()
  myTest = myTest.data

  logger.error({
    myTest: myTest
  })
  //获取所有考试题目
  var allTest = await db_test.where({
    flag: 'test'
  }).get()
  allTest = allTest.data

  logger.error({
    allTest: allTest
  })
  //将两类数据整合
  for (let i = 0; i < allTest.length; i++) {
    for (let j = 0; j < myTest.length; j++) {
      logger.error({
        allTest_TestName: allTest[i].TestName,
        myTest_TestName: myTest[i].testName
      })
      //赋值状态
      if (allTest[i].TestName == myTest[j].testName) {
        allTest[i].status = myTest[j].testStatus
        allTest[i].publishId = myTest[j]._id
        break
      }
    }
  }
  var result = {
    testList: allTest,
    isAdmin: isAdmin
  }
  return result;
}


//获取所有答案
async function getUserAnswers(deleteResult) {
  var allAnswers = await db_testAnswer.get()
  var result = {
    allAnswers: allAnswers.data,
    deleteResult: deleteResult
  }
  return result
}

//删除用户的答案
async function deleteAnswerById(event) {
  var deleteResult = await db_testAnswer.doc(event.answerId).remove()
  return getUserAnswers(deleteResult)
}